package es.ibm.santillana.mdm.entryPreview.catalog;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.json.java.JSONArray;
import com.ibm.json.java.OrderedJSONObject;
import com.ibm.pim.catalog.Catalog;
import com.ibm.pim.catalog.CatalogManager;
import com.ibm.pim.catalog.item.Item;
import com.ibm.pim.collaboration.CheckoutStatus;
import com.ibm.pim.collaboration.CollaborationAreaManager;
import com.ibm.pim.collaboration.CollaborationItem;
import com.ibm.pim.collaboration.CollaborationStep;
import com.ibm.pim.collaboration.ItemCollaborationArea;
import com.ibm.pim.common.ProcessingOptions;
import com.ibm.pim.common.exceptions.PIMInvalidOperationException;
import com.ibm.pim.context.Context;
import com.ibm.pim.context.PIMContextFactory;
import com.ibm.pim.hierarchy.Hierarchy;
import com.ibm.pim.hierarchy.HierarchyManager;
import com.ibm.pim.hierarchy.category.Category;
import com.ibm.pim.lookuptable.LookupTable;
import com.ibm.pim.lookuptable.LookupTableEntry;
import com.ibm.pim.lookuptable.LookupTableManager;
import com.ibm.pim.spec.SecondarySpec;
import com.ibm.pim.system.UIHelper;
import com.ibm.pim.utils.Logger;
import com.ibm.pim.web.framework.dispatcher.AsyncEnabled;
import com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled;

import es.ibm.santillana.mdm.common.bussinesmodel.ConfigModel;
import es.ibm.santillana.mdm.common.util.ConstSantillana;
import es.ibm.santillana.mdm.common.util.SantillanaLogger;
import es.ibm.santillana.mdm.state.StateManager;

public class ExtenderArticulo implements AsyncEnabled,RequestResponseEnabled{
	
	HttpServletRequest request;
	HttpServletResponse response;
	
	String responseContent ="";

	/* (sin Javadoc) 
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getContentType()
	 */
	public String getContentType() {
		
		return JSON;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.AsyncEnabled#getResponseContent()
	 */
	public String getResponseContent() {
		
		return responseContent;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	/* (sin Javadoc)
	 * @see com.ibm.pim.web.framework.dispatcher.RequestResponseEnabled#setResponse(javax.servlet.http.HttpServletResponse)
	 */
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public static void checkOutItem(Item itm, String sPais) {
		System.out.println("voy al temita");
		CollaborationAreaManager caMager = PIMContextFactory.getCurrentContext().getCollaborationAreaManager();
		Context ctx = PIMContextFactory.getCurrentContext();
		String colAreaName = ConfigModel.getMoficationColAreaFromCountry(sPais); //TODO: coger el pais del user
		System.out.println(colAreaName);
		ItemCollaborationArea colArea = (ItemCollaborationArea) caMager.getCollaborationArea(colAreaName);
		ProcessingOptions po = colArea.getProcessingOptions();
		po.setPostScriptProcessing(false);
		System.out.println(colArea);
		CheckoutStatus status = colArea.checkoutAndWaitForStatus(itm);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
public static String getCollaborationItemURL(Item itm, String sPais){
		
		Context ctx = PIMContextFactory.getCurrentContext();
		CollaborationAreaManager colMng = ctx.getCollaborationAreaManager();
		UIHelper ui = ctx.getUIHelper();
		Logger log = SantillanaLogger.getLogger();
		System.out.println("getting url");
		
		String colAreaName = ConfigModel.getMoficationColAreaFromCountry(sPais); 
		ItemCollaborationArea colArea = (ItemCollaborationArea) colMng.getCollaborationArea(colAreaName);
		log.logInfo("pk "+itm.getPrimaryKey());
		
		
		CollaborationItem itmCol = colArea.getCheckedOutItem(itm.getPrimaryKey());
		if (itmCol!= null){
			System.out.println("no nulo");
		}
		
		CollaborationStep step = colArea.getStep(ConstSantillana.STEP_ENRIQUECER_MODIFI);
	
		String url = ui.getCollaborationEntryURL(step, itmCol);
		
		return url;
	}
	
	/**
	 * @throws Exception 
	 */
	public void extenderArticulo() throws Exception {
		
		JSONArray aListOrden = new JSONArray();
		Logger log = SantillanaLogger.getLogger();
		OrderedJSONObject urlJSON = new OrderedJSONObject();
		
		String pkArticulo = request.getParameter("pkArticulo"); //5603
		String pkSociedad = request.getParameter("pkSociedad"); //0677
		
		System.out.println("Extender: pkArt="+pkArticulo+";pkSoc="+pkSociedad);
		
		Context ctx = PIMContextFactory.getCurrentContext();
		LookupTableManager lkpMan = ctx.getLookupTableManager();
		LookupTable lkp = lkpMan.getLookupTable("System Parameter LKP");
		LookupTableEntry itmLkpUser = lkp.getLookupTableEntry("user.admin.name");
		LookupTableEntry itmLkpPwd = lkp.getLookupTableEntry("user.admin.pwd");
		LookupTableEntry itmLkpCmp = lkp.getLookupTableEntry("company");
		
		String user = (String) itmLkpUser.getAttributeValue("Code_Value_LTS/Value");
		String pwd = (String) itmLkpPwd.getAttributeValue("Code_Value_LTS/Value");
		String cmp = (String) itmLkpCmp.getAttributeValue("Code_Value_LTS/Value");
		
		
		ctx = PIMContextFactory.getContext(user, pwd, cmp);
		HierarchyManager hyMng = ctx.getHierarchyManager();
		CatalogManager ctgMng = ctx.getCatalogManager();
		
		// Cargar jerarquias
		Hierarchy hySociedades = hyMng.getHierarchy(ConstSantillana.JERARQUIA_PAISES);
		Hierarchy hySociedadesTipo = hyMng.getHierarchy(ConstSantillana.JERARQUIA_SOCIEDADES);
		Hierarchy hyTipologia = hyMng.getHierarchy(ConstSantillana.JERARQUIA_TIPO_DE_PRODUCTO);
		
		// Cargar item del catalogo Articulos
		
		
		Catalog ctg = ctgMng.getCatalog(ConstSantillana.MAESTRO_ARTICULOS);
		
		ProcessingOptions po = null;
		
		
		po = ctg.getProcessingOptions();
		po.setAllProcessingOptions(false);
		Item itm = ctg.getItemByPrimaryKey(pkArticulo);
		
		// Cargar categoria buscada de la jerarquia Sociedad
		Iterator<Category> it = hySociedades.getCategories().iterator();
		while(it.hasNext()) {
			Category c = it.next();
			System.out.println(c.getDisplayName());
			System.out.println(c.getPrimaryKey());
		}
		Category catSociedad = hySociedades.getCategoryByPrimaryKey(pkSociedad);
		
		// Cargar la categoria de la jerarquia tipologia del item buscado
		// Siempre habra un elemento. Es una regla de negocio
		Category catTipologia = itm.getCategories(hyTipologia).iterator().next(); 
		
		// La PK de SociedadTipo es la concatenacion del PK de Sociedad y Tipologia
		String pkSociedad_Tipo = catSociedad.getPrimaryKey() + catTipologia.getPrimaryKey();
		
		// Cargar categoria de la jerarquia Sociedad-Tipo del PK Sociedad-Tipo
		Category catSociedadTipo = hySociedadesTipo.getCategoryByPrimaryKey(pkSociedad_Tipo);
		
		Collection<SecondarySpec> colSociedad = catSociedad.getItemSecondarySpecs();
		Iterator <SecondarySpec> itSpecs = colSociedad.iterator();
		String sSpecState = null;
		while (itSpecs.hasNext()) {
			SecondarySpec secSpec = itSpecs.next();
			String name = secSpec.getName();
			if (!name.contains("SEARCH")) {
				sSpecState = name;
			}
		}
		
		// Mapear item a Categoria sociedad-Tipo
		
		
		checkOutItem(itm,catSociedad.getParent().getPrimaryKey());
		String url = getCollaborationItemURL(itm,catSociedad.getParent().getPrimaryKey());
		CollaborationAreaManager  colMng = ctx.getCollaborationAreaManager(); 
        //TODO Quitar Colombia hardcoding!
		ItemCollaborationArea colArea = (ItemCollaborationArea) colMng.getCollaborationArea(ConfigModel.getMoficationColAreaFromCountry(catSociedad.getParent().getPrimaryKey())); 
		String sPkwfl = itm.getPrimaryKey(); 
		
		
		
		
		System.out.println("Ojito");
		System.out.println(catSociedad.getParent().getPrimaryKey());
		
		        
		System.out.println(sPkwfl);  
		System.out.println(colArea);
		

		CollaborationItem itmCol = colArea.getCheckedOutItem(sPkwfl); 
	
		itmCol.mapToCategory(catSociedadTipo);
		itmCol.mapToCategory(catSociedad);
		StateManager.setState(itmCol, "Y1", sSpecState);
		itmCol.save();		

		urlJSON.put("url", url);
		aListOrden.add(urlJSON);
		
		responseContent = aListOrden.serialize(true);
		
		
	}	
}
